package pe.com.certicom.ittsa.control.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import pe.com.certicom.ittsa.model.bean.BeanGeoCode;

public class KMLReader {
	private static String KEY = "ABQIAAAAveg2CpgMCtgxFX9r1kDx6xTD07Z-7nQfgYdpPbl9uCIkZE09QxS9RvNCqvGU6mDtC_Syv0afzb1kVA";
	private static String URL = "http://maps.google.com/maps/geo?";

	public static BeanGeoCode readKML(String coord_x, String coord_y)
			throws Exception {

		String s = URL + "q=" + coord_x + "," + coord_y + "&output=xml&key="
				+ KEY;
		String xml = "";

		BeanGeoCode bgeocode = new BeanGeoCode();

		Document dom;

		try {

			URL url1 = new URL(s);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url1.openStream()));
			String str;
			while ((str = in.readLine()) != null) {

				xml = xml + str.trim();

			}

			in.close();

			InputStream is = new ByteArrayInputStream(
					xml.getBytes("iso-8859-1"));

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			dom = db.parse(is);

			Element root = dom.getDocumentElement();
			NodeList responseNodes = root.getElementsByTagName("Response");

			if (responseNodes.getLength() > 0) {
				Element responseNode = (Element) responseNodes.item(0);
				Element status = getOneChild(responseNode, "Status");
				String code = getChildString(status, "code", null);
				if ("620".equals(code)) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException ie) {
						System.out.println(ie.getMessage());
					}
					bgeocode.setFlag(1);
					return bgeocode;
				}
				if ("200".equals(code)) {
					bgeocode.setFlag(2);
					NodeList placemarkNodes = root
							.getElementsByTagName("Placemark");
					for (int i = 0; i < placemarkNodes.getLength(); i++) {
						Element placemarkNode = (Element) placemarkNodes
								.item(i);
						String address = getChildString(placemarkNode,
								"address", null);
						bgeocode.setLocalizacion(address);
						Element addressDetails = getOneChild(placemarkNode,
								"AddressDetails");

						if (addressDetails != null) {
							Element country = getOneChild(addressDetails,
									"Country");
							if (country != null) {
								Element administrativeArea = getOneChild(
										addressDetails, "AdministrativeArea");
								String countryNameCode = getChildString(
										country, "CountryNameCode", null);
								String countryName = getChildString(country,
										"CountryName", null);
								bgeocode.setCodigoPais(countryNameCode);
								bgeocode.setPais(countryName);
								if (administrativeArea != null) {
									Element locality = getOneChild(
											administrativeArea, "Locality");
									String administrativeAreaName = getChildString(
											administrativeArea,
											"AdministrativeAreaName", null);
									bgeocode.setDepartamento(administrativeAreaName);
									if (locality != null) {
										Element dependentLocality = getOneChild(
												locality, "DependentLocality");
										String localityName = getChildString(
												country, "LocalityName", null);
										bgeocode.setProvincia(localityName);
										if (dependentLocality != null) {
											Element thoroughfare = getOneChild(
													dependentLocality,
													"Thoroughfare");
											String dependentLocalityName = getChildString(
													dependentLocality,
													"DependentLocalityName",
													null);
											bgeocode.setDistrito(dependentLocalityName);
											if (thoroughfare != null) {
												String thoroughfareName = getChildString(
														thoroughfare,
														"ThoroughfareName",
														null);
												bgeocode.setDireccion(thoroughfareName);
											}
										} else {
											Element thoroughfare = getOneChild(
													locality, "Thoroughfare");
											String dependentLocalityName = "";
											bgeocode.setDistrito(dependentLocalityName);
											if (thoroughfare != null) {
												String thoroughfareName = getChildString(
														thoroughfare,
														"ThoroughfareName",
														null);
												bgeocode.setDireccion(thoroughfareName);
											}
										}
									} else {
										Element dependentLocality = getOneChild(
												administrativeArea,
												"DependentLocality");
										String localityName = "";
										bgeocode.setProvincia(localityName);
										if (dependentLocality != null) {
											Element thoroughfare = getOneChild(
													dependentLocality,
													"Thoroughfare");
											String dependentLocalityName = getChildString(
													dependentLocality,
													"DependentLocalityName",
													null);
											bgeocode.setDistrito(dependentLocalityName);
											if (thoroughfare != null) {
												String thoroughfareName = getChildString(
														thoroughfare,
														"ThoroughfareName",
														null);
												bgeocode.setDireccion(thoroughfareName);
											}
										} else {
											Element thoroughfare = getOneChild(
													administrativeArea,
													"Thoroughfare");
											String dependentLocalityName = "";
											bgeocode.setDistrito(dependentLocalityName);
											if (thoroughfare != null) {
												String thoroughfareName = getChildString(
														thoroughfare,
														"ThoroughfareName",
														null);
												bgeocode.setDireccion(thoroughfareName);
											}
										}
									}
								}
							}
						}
					}
				} else {
					return bgeocode;
				}
			}
		} catch (Exception e) {
			throw e;
		}

		return bgeocode;

	}

	protected static String getChildString(Element elmt, String name, String def) {
		Element child = getOneChild(elmt, name);
		String text = child != null ? child.getTextContent() : null;
		return text != null && text.length() > 0 ? text : def;
	}

	protected static Element getOneChild(Element elmt, String name) {
		NodeList list = elmt.getElementsByTagName(name);
		return list != null && list.getLength() > 0 ? (Element) list.item(0)
				: null;
	}
}
